package com.lzc.springcloud.authserver.application;

import com.lzc.springcloud.authserver.application.representation.User;
import com.lzc.springcloud.authserver.domain.identity.SysRoleEntity;
import com.lzc.springcloud.authserver.domain.identity.SysUserEntity;
import com.lzc.springcloud.authserver.infrastructure.persistence.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2017/6/7.
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserRepository userRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity user = userRepository.findByUsername(username);
        Set<String> roles = new HashSet<>();
        for (SysRoleEntity sysRoleEntity : user.roleEntities()) {
            roles.add(sysRoleEntity.getRoleName());
        }
        List<GrantedAuthority> grantedAuthorities = this.buildGrantedAuthorities(roles);
        User users = this.buildUserForAuthentication(user, grantedAuthorities);
        return users;
    }

    private List<GrantedAuthority> buildGrantedAuthorities(Set<String> roles) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        roles.forEach(role->grantedAuthorities.add(new SimpleGrantedAuthority(role)));
        return grantedAuthorities;
    }

    private List<GrantedAuthority> buildGrantedAuthorities(String role) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        grantedAuthorities.add(new SimpleGrantedAuthority(role));
        return grantedAuthorities;
    }

    private User buildUserForAuthentication(SysUserEntity user, List<GrantedAuthority> authorities){
        String username = user.username();
        String password = user.password();
        return new User(user.userId()+"", username, password, "", authorities);
    }
}
